layui.config({
    base: '/static/client/cropper/layui_modules/' //你存放新模块的目录，注意，不是layui的模块目录
}).use('cropperUpload'); //加载入口


let formCoverUpload;
let coverupload;

let images = [];

//一般直接写在一个js文件中
layui.use(['layer', 'form', 'element', 'laydate', 'cropperUpload', 'layedit', 'laypage', 'table'], function () {
    let layer = layui.layer
        , form = layui.form;
    let element = layui.element;
    let laydate = layui.laydate;
    let cropperUpload = layui.cropperUpload;
    let layedit = layui.layedit;
    let laypage = layui.laypage;

    let table = layui.table;
    //执行一个laydate实例
    laydate.render({
        elem: '.date' //指定元素
    });

    //日期时间范围选择
    laydate.render({
        elem: '.rangeTime'
        , range: '~' //或 range: '~' 来自定义分割字符
    });

    let pageIndex = 1;
    let tempFiles = [];
    //表单照片裁剪图片组件
    formCoverUpload = cropperUpload.init({
        select: "#formCoverUpload",
        aspectRatio: 228 / 128,
        imgWidth: 2280 / 2,
        imgHeight: 1280 / 2,
        formDataId: "#blogForm",
        multiple: true,
        success: function (base64Img, blog, that) {  //base64Img  base64格式图片    blog  二进制图

            let index = tempFiles.length;
            $(that.defaultOptions.eventEl).before('  <div class="showImg">' +
                '                                    <img width="228"  id="' + blog.name + '"   height="128" src="' + base64Img + '">' +
                '                                    <div> <span><i class="layui-icon  layui-icon-delete"></i>删除</span>  </div>' +
                '                                </div>')

            $(".showImg  span").unbind();
            $(".showImg  span").bind("click", function () {
                let tempImgDiv = $(this).parent().parent();
                if (that.removeFile(tempImgDiv.find("img").attr("id"))) {
                    tempImgDiv.remove();
                }
            });
        }
    })

    //博客表单提交
    form.on('submit(formAlbum)', function (data) {

        if ($(data.form), find(".showImg").length == 0) {
            layer.tips("请选择图片", "#formCoverUpload", {tips: [1, 'red']});
            return false;
        }
        let flag = "add";
        if ($(data.form).find("[name='uuid']").length > 0) {
            flag = "update"
        }
        formCoverUpload.ajaxPost("/album/" + flag + "-album", function (res) {
            if (res.success && flag == "add") {
                data.form.reset();
                $(".showImg").remove();
                formCoverUpload.formData = new FormData();
            }
            layer.msg(res.content);
        });
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });


    $("#addressBtn").click(function () {
        let input = $(this).prev();
        //自定页
        let cf = layer.open({
            type: 2,
            title: "地图获取位置-【<span id='selectAddress' style='color:green;'>请搜索选择地址</span>】",
            skin: 'layui-layer-demo', //样式类名
            closeBtn: 1,
            anim: 2,
            area: ['1000px', '600px'],
            content: '/client/map.html',
            btn: ["确定", "取消"],
            yes: function () {
                let text = $("#selectAddress").text();
                if (text.indexOf("请搜索选择地址") != 0) {
                    input.val(text.split("地址")[1].trim());
                    layer.close(cf);
                } else {
                    layer.msg("请输入关键词在点击确定")
                }
            }

        });
    })

    //数据校验
    form.verify({
        pass: [/^[\S]{6,12}$/, '密码必须6到12位，且不能出现空格'],
        repass: function (value, item) {
            if (!/^[\S]{6,12}$/.test(value)) {
                return '密码必须6到12位，且不能出现空格';
            }
            if (value != $('[type=password]').val()) {
                return '二次密码输入不一致';
            }
        },
        summary: [/^.{1,200}$/, "摘要必须在200字以内"],
        nickName: [/^[\u4e00-\u9fa5_a-zA-Z0-9]{1,15}$/, '昵称15个字符内，只能是字母数字下划线或者中文'],
        captcha: [/^[a-zA-Z0-9]{4,5}$/, "请输入有效验证码"],
        title: [/^[\u4e00-\u9fa5_a-zA-Z0-9]{1,50}$/, '标题50个字符内，只能是字母数字下划线或者中文']
    });

    //切换选项卡
    $(".site-tree-noicon [lay-event]").click(function () {
        let f = $(this).attr("lay-event");
        if ($("[lay-id='" + f + "']").length == 0) {
            window.location = $(this).attr("lay-url");
        } else {
            $(".site-tree-noicon").removeClass("site-tree-active");
            $(this).parent().addClass("site-tree-active");
            element.tabChange('tableInfo', $(this).attr("lay-event"));
        }
    })

    element.on('tab(tableInfo)', function (data) {
        let layid = $(this).attr("lay-id");
        location.hash = 'tab=' + $(this).attr('lay-id');
        $(".site-tree-noicon").removeClass("site-tree-active");
        $("[lay-event=" + layid + "]").parent().addClass("site-tree-active");

        if (data.index == 1) {
            loadAlbum(pageIndex)
        } else if (data.index == 2) {
            loadAlbum(pageIndex, true);
        }
    });

    //Hash地址的定位
    var layid = location.hash.replace(/^#tab=/, '');
    element.tabChange('tableInfo', layid);

    $(".showImg  span").bind("click", function () {
        let tempImgDiv = $(this).parent().parent();
        $.ajax({
            url: "/album/deleteImg",
            data: "uuidImg=" + tempImgDiv.find("img").attr("id") + "&token=" + $("[name='token']").val(),
            type: "POST",
            dataType: "JSON",
            success: function (res) {
                if (res.success) {
                    tempImgDiv.remove();
                }
                layer.msg(res.content);
            }, error: function () {
                layer.msg("服务器异常");
            }
        });


    });


    loadAlbum(pageIndex);

    form.on('submit(findListAlbum)', function (data) {
        loadAlbum(1, false);
        return false;
    });
    form.on('submit(findDraftAlbum)', function (data) {
        loadAlbum(1, true);
        return false;
    });


    function loadAlbum(pageIndex, draft) {
        if (draft == null) {
            draft = false
        }
        $("#searchForm" + (draft ? "1" : "") + "[name='pageIndex']").val(pageIndex);
        $.ajax({
            url: "/album/" + draft + "-loadAlbum",
            data: $("#searchForm" + (draft ? "1" : "")).serializeJson(),
            type: "POST",
            dataType: "JSON",
            success: function (res) {
                if (res.dataList != null && res.dataList.length > 0) {
                    $("#albumTable" + (draft ? "1" : "") + " tbody").html(createHtml(res.dataList, draft));
                    initEvent(draft, res);
                } else {
                    let html = '<tr>' +
                        '            <td colspan="6" style="text-align: center;"> <h3>暂无数据</h3></td> ' +
                        '            </td>';
                    $("#albumTable" + (draft ? "1" : "") + "tbody").html(html);
                }
                form.render();
            }, error: function () {
                layer.msg("服务器异常");
            }
        })

    }

    function toViewJson(img) {
        let imgs = img.url.split(",");
        let ar = [];
        for (url of imgs) {
            if (url != "") {
                ar.push({alt: img.title, pid: new Date(), src: url, thumb: ""})
            }
            let json = {title: img.title, id: img.uuid, start: 0, data: ar}
            images[img.uuid] = json;
        }
    }

    function createHtml(dataList, draft) {
        let html = '';
        for (img of dataList) {
            toViewJson(img);

            let cover = img.url.split(",");
            let ck = img.status == 0 ? "checked" : "";
            let button = '';

            if (draft) {
                button = '  <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" blog-id="' + img.uuid + '"   lay-event="return" >' +
                    '                                                    <i class="layui-icon layui-icon-edit"></i>' +
                    '                                                    恢&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;复' +
                    '                                                </button> <br>' +
                    '                                                <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" blog-id="' + img.uuid + '" lay-event="delete" >' +
                    '                                                    <i class="layui-icon layui-icon-delete"></i>' +
                    '                                                    删&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;除' +
                    '                                                </button>'
            } else {
                button = '                                        <button type="button"  blog-id="' + img.uuid + '"  class="layui-btn layui-btn-xs layui-btn-normal  cover">' +
                    '                                            <i class="layui-icon layui-icon-picture-fine"></i>' +
                    '                                            更换封面' +
                    '                                        </button><br>' +
                    '                                        <button type="button" class="layui-btn layui-btn-xs layui-btn-primary"  blog-id="' + img.uuid + '" lay-event="lookBlog">' +
                    '                                            <i class="layui-icon layui-icon-search"></i>' +
                    '                                            查&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;看' +
                    '                                        </button> <br>' +
                    '                                        <button type="button" class="layui-btn layui-btn-xs layui-btn-normal"  blog-id="' + img.uuid + '"   lay-event="editBlog" >' +
                    '                                            <i class="layui-icon layui-icon-edit"></i>' +
                    '                                            编&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;辑' +
                    '                                        </button> <br>' +
                    '                                        <button type="button" class="layui-btn layui-btn-xs layui-btn-danger"  blog-id="' + img.uuid + '"  lay-event="draft" >' +
                    '                                            <i class="layui-icon layui-icon-delete"></i>' +
                    '                                            移送草稿箱' +
                    '                                        </button>'
            }

            html += '          <tr>' +
                '                                    <td>' +
                '                                        <img blog-id="' + img.uuid + '"    src="' + cover[cover.length - 2] + '">' +
                '                                    </td>' +
                '                                    <td>' + img.title + '</td>' +
                '                                    <td>' + img.address + '</td>' +
                '                                    <td>' +
                '                                        <input type="checkbox" ' + ck + '  blog-id="' + img.uuid + '"   lay-filter="status"    name="zzz" lay-skin="switch" lay-text="已发布|未发布">' +
                '                                    </td>' +
                '                                    <td>' + img.createtime + '</td>' +
                '                                    <td>' +
                button +
                '                                    </td>' +
                '                                </tr>'

        }
        return html;
    }


    function initEvent(draft, res) {

        //执行一个laypage实例
        let page = laypage.render({
            curr: res.pageIndex,
            limit: 5,
            elem: 'blogList-page' + (draft ? '1' : '') //注意，这里的 test1 是 ID，不用加 # 号
            , count: res.count //数据总数，从服务端得到
            , jump: function (obj, first) {
                //obj包含了当前分页的所有参数，比如：
                console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                console.log(obj.limit); //得到每页显示的条数
                //首次不执行
                if (!first) {
                    loadAlbum(obj.curr, draft);
                }
            }
        });
        /**
         * 预览图片
         * @param obj
         */
        $(".infoTable tr>td img").click(function () {
            previewImg($(this));

        })

        function previewImg(obj) {

            // $.getJSON('/static/client/js/album.json', function (json) {
            //     layer.photos({
            //         photos: json
            //         , anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
            //     });
            // });
            layer.photos({
                photos: images[obj.attr("blog-id")]
                , anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
            });
        }


        //操作
        $(".infoTable  [lay-event]").click(function () {
            let event = $(this).attr("lay-event");
            let uuid = $(this).attr("blog-id");
            let tr = $(this).parent().parent()
            if (event == "lookBlog") {
                openUrlWindow("/album/look-Album?uuid=" + uuid + "&token=" + $("[name='token']").val());

            } else if (event == "editBlog") {
                openUrlWindow("/album/update-Album?uuid=" + uuid + "&token=" + $("[name='token']").val());

            } else {
                $.ajax({
                    url: "/album/edit/" + event + "/" + uuid,
                    data: "token=" + $("[name='token']").val(),
                    type: "POST",
                    dataType: "JSON",
                    success: function (res) {
                        if (res.success) {
                            tr.remove();
                            loadAlbum(pageIndex, event == "draft" ? true : false);
                        }
                        layer.msg(res.content);
                    }, error: function () {
                        layer.msg("服务器异常");
                    }
                });

            }
        })
        form.on('switch(status)', function (data) {
            let origin = data.elem.checked;
            let uuid = $(data.elem).attr("blog-id");
            let event = (data.elem.checked) ? "send" : "cancel";
            let str = "";
            if (origin) {
                str = "设置发部状态吗？";
            } else {
                str = "设置为未发布状态吗?";
            }
            let cf = layer.confirm('你确定要' + str, {
                time: 20000, //20s后自动关闭
                btn: ['确认', '取消'],
                yes: function () {
                    layer.close(cf)
                    $.ajax({
                        url: "/album/edit/" + event + "/" + uuid,
                        data: "token=" + $("[name='token']").val(),
                        type: "POST",
                        dataType: "JSON",
                        success: function (res) {
                            if (res.success) {
                                data.elem.checked = !origin
                                form.render();
                            }
                            layer.msg(res.content);
                        }, error: function () {
                            data.elem.checked = !origin
                            form.render();
                            layer.msg("服务器异常");
                        }
                    })
                },
                btn2: function () {
                    data.elem.checked = !origin;
                    form.render();
                }, cancel: function () {
                    data.elem.checked = !origin;
                    form.render();
                }
            });
        });

        function openUrlWindow(url, title) {
            if (title == null) title = "正在编辑"
            let ww = layer.open({
                type: 2,
                title: title,
                skin: 'layui-layer-demo', //样式类名
                closeBtn: 0, //不显示关闭按钮
                anim: 2,
                shadeClose: true, //开启遮罩关闭
                content: url,
                closeBtn: 1,
                success: function () {
                    $(".layui-layer-content").attr("style", "height:100%")
                    layer.full(ww);
                    setTimeout(function () {

                        layer.tips('点击这里关闭！', '.layui-layer-close', {
                            tips: [1, 'red'],
                            time: 4000
                        });
                    }, 300)
                }
            });
        }


        //封面裁剪图片组件
        coverupload = cropperUpload.init({
            select: ".cover",
            aspectRatio: 16 / 9,
            success: function (base64Img, blog, that) {  //base64Img  base64格式图片    blog  二进制图
                //获得触发的按钮
                let btn = that.defaultOptions.eventEl;
                //本地直接更换
                //$(btn).parent().parent().find("td:first>img").attr("src",base64Img)
                //提交至服务器
                coverupload.ajaxPost("/album/updateCover", function (data) {
                    if (data.success) {
                        let as = images[btn.attr("blog-id").trim()].data;
                        for (u of as) {
                            if (u.src.trim() == $(btn).parent().parent().find("td:first>img").attr("src").trim) {
                                u.src = data.data;
                            }
                        }
                        $(btn).parent().parent().find("td:first>img").attr("src", data.data)
                    } else {
                        layer.msg("更换封面失败！")
                    }
                }, {uuid: btn.attr("blog-id"), token: $("[name='token']").val()})
            }
        })
    }


});